package com.zhong;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

/**
 * @author zhong
 * @version 1
 * @date 2022/04/09
 * @contact 1478168700@qq.com
 **/
public class TestTransformer implements ClassFileTransformer {

    public final String TEST_CLASS_NAME = "com.zhong.OneService";

    public final String METHOD_NAME = "hello";


    public byte[] transform(ClassLoader loader,
                            String className,
                            Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain,
                            byte[] classfileBuffer) throws IllegalClassFormatException {

//      System.out.println("className : " + className);

        String finalClassName = className.replace("/", ".");

        if (TEST_CLASS_NAME.equals(finalClassName)) {
            System.out.println("class name 匹配上了 !");

            CtClass ctClass;

            try {
                ctClass = ClassPool.getDefault().get(finalClassName);
                System.out.println("ctClass is OK !");
                CtMethod ctMethod = ctClass.getDeclaredMethod(METHOD_NAME);
                //在目标方法前后，插入代码
                ctMethod.insertBefore("System.out.println(\"--- before doBusiness ---\");");
                ctMethod.insertAfter("System.out.println(\"--- after doBusiness ---\");");

                System.out.println("CtMethod is OK !");
                ctMethod.insertBefore("System.out.println(\"字节码添加成功，打印日志 !\");");
                return ctClass.toBytecode();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
        }

        return null;
    }
}
